import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { AlainService } from '@shared/itcore/services/alain.service';
import { NzModalComponent, NzTreeComponent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/ng-zorro-antd';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-itcore-modal-tree',
  template: `
    <nz-modal
      #modal
      [(nzVisible)]="visible"
      [nzTitle]="title"
      [nzClosable]="false"
      [nzFooter]="permissFooter"
      [nzBodyStyle]="{ 'max-height': '600px', 'overflow-y': 'auto' }"
    >
      <nz-alert *ngIf="loading" nzType="info" nzMessage="正在加载树数据，请稍候……"></nz-alert>

      <nz-tree
        #tree
        *ngIf="treeData.length > 0"
        [nzData]="treeData"
        [nzCheckedKeys]="defaultCheckedKeys"
        nzCheckable
        nzMultiple
        [nzExpandAll]="false"
      ></nz-tree>
      <ng-template #permissFooter>
        <button nz-button type="button" (click)="close()">关闭</button>
        <button nz-button type="submit" [nzType]="'primary'" (click)="submit()" [nzLoading]="http.loading">
          保存
        </button>
      </ng-template>
    </nz-modal>
  `,
  styles: [],
})
export class ModalTreeComponent {
  @Input() title: string;
  @Input() treeDataUrl: string;
  @Input() submitACL: string;
  @Output() submited: EventEmitter<NzTreeNode[]> = new EventEmitter<NzTreeNode[]>();

  visible: boolean;
  treeData: NzTreeNodeOptions[] = [];
  @ViewChild('modal', { static: false }) modal: NzModalComponent;
  @ViewChild('tree', { static: false }) tree: NzTreeComponent;

  // 默认选中集合
  defaultCheckedKeys = [];

  constructor(public http: _HttpClient, private alain: AlainService) { }

  // TODO: 不知原因，nzAfterOpen事件会重复调用，暂时使用loading来阻隔
  loading = false;
  private loadTreeData() {
    if (this.loading) {
      return;
    }
    this.loading = true;
    const url = this.treeDataUrl;
    if (!url) {
      return;
    }
    this.http
      .get(url)
      .pipe(
        map((res) => {
          this.alain.ToNzCheckTreeId(res, this.defaultCheckedKeys);
          return this.alain.ToNzTreeData(res);
        }),
      )
      .subscribe((res: NzTreeNodeOptions[]) => {
        this.treeData = res;
        this.loading = false;
      });
  }

  open() {
    this.modal.open();
    setTimeout(() => {
      this.loadTreeData();
    }, 10);
  }
  nzAfterOpen() { }
  close() {
    this.treeData = [];
    this.defaultCheckedKeys = [];
    this.modal.destroy();
  }

  submit() {
    const nodes = this.tree.nzTreeService.getCheckedNodeList();
    this.submited.emit(nodes);
  }
}
